import { selectMeasuringToolsAnnexPage, deleteMeasuringToolsAnnexById } from '@/api/modules/measuringTools'

/** 计量器具报告 */
export default function useAnnexReports() {
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useShallowState<any[]>([])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: 10,
    total: 0,
  })

  async function getLists(toolId: number) {
    setLoading(true)
    try {
      const { data } = await selectMeasuringToolsAnnexPage(
        toolId,
        pagination.pageNumber,
        pagination.pageSize,
      )
      setTableData(data.records ?? [])
      pagination.total = data.total
    }
    finally {
      setLoading(false)
    }
  }

  async function confirmDel() {
    return ElMessageBox.confirm(
      '确认要删除该数据吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
  }

  async function deleteAnnexRecord(id: number) {
    const res = await confirmDel().catch(e => e)
    if (res === 'confirm') {
      await deleteMeasuringToolsAnnexById(id)
      setTableData(unref(tableData).filter(item => item.id !== id))
      ElMessage.success('删除成功')
    }
  }

  function downloadPDF(url: string, filename: string) {
    fetch(url)
      .then(response => response.blob()) // 获取blob数据
      .then((blob) => {
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = url
        a.download = filename
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url) // 清理内存
      })
      .catch(err => console.error('Error downloading the file', err))
  }

  function preview(url: string) {
    window.open(url)
  }

  return {
    loading,
    tableData,
    pagination,
    getLists,
    deleteAnnexRecord,
    preview,
    downloadPDF,
  }
}
